﻿//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using Cinemachine;
using GameFramework;
using GameFramework.Fsm;
using System;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace Adventure
{
    public class EnemyEntity : FigureObject
    {
        public bool isGround;      
        public bool touchLeftWall;
        public bool touchRightWall;

        public Vector2 groundOffset;      
        public Vector2 touchLeftOffset;
        public Vector2 touchRightOffset;


        private float checkRadius;        
       
        public Rigidbody2D rb;
        public Animator anim;

        public float currentSpeed;
        public float normalSpeed;
        public float chaseSpeed;

        public bool currentHit;
        public bool animWalk, animRun, animHit, animDeath,  animAttack;

        public Vector3 faceDir;
        public Vector2 rayOffsetPoint;
        public int findPlayerRayCount = 10;
        public bool findPlayer;
        public Transform playerTran;

        public EnemyEntityData enemyEntityData;
        protected override void OnInit(object userData)
        {
            base.OnInit(userData);

            checkRadius = 0.1f;          
            

            rb = GetComponent<Rigidbody2D>();
            anim = GetComponent<Animator>();

            gameObject.SetLayerRecursively(Constant.Layer.EnemyId);
        }

        protected override void OnShow(object userData)
        {
            base.OnShow(userData);
            if (userData!=null)
            {
                enemyEntityData = (EnemyEntityData)userData;
            }
        }
        protected override void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(elapseSeconds, realElapseSeconds);          

            isGround = Physics2D.OverlapCircle((Vector2)transform.position + groundOffset, checkRadius, 1 << Constant.Layer.GroundId);
            touchLeftWall = Physics2D.OverlapCircle((Vector2)transform.position + touchLeftOffset, checkRadius, 1 << Constant.Layer.GroundId);
            touchRightWall = Physics2D.OverlapCircle((Vector2)transform.position + touchRightOffset, checkRadius, 1 << Constant.Layer.GroundId);

            anim.SetBool("Walk", animWalk);//野猪
            anim.SetBool("Run", animRun);//野猪
            anim.SetBool("Hit", animHit);//野猪

           // anim.SetBool("Death", animDeath);
          
         //   anim.SetBool("Attack", animAttack);

            faceDir = new Vector3(transform.localScale.x * -1, 1, 1);

            RayCheckPlayer();
        }

        public void HitAddForce(Entity entity)
        {
            if (!entity) return;
          
            int direction = entity.transform.position.x > transform.position.x ? -1 : 1;
            float force = 10;

            if (direction == 1)
            {
                // entity在右边
                rb.AddForce((Vector3.right + Vector3.up) * force, ForceMode2D.Impulse);
            }
            if (direction == -1)
            {
                // entity在左边
                rb.AddForce((Vector3.left + Vector3.up) * force, ForceMode2D.Impulse);
            }
        }

        /// <summary>
        /// 蜜蜂的检测不一样,野猪和蜗牛是一样的前方检测
        /// </summary>
        public virtual void RayCheckPlayer()
        {
            playerTran = Physics2D.Raycast((Vector2)transform.position + rayOffsetPoint, new Vector2(faceDir.x, 0), findPlayerRayCount, 1 << Constant.Layer.PlayerId).collider?.transform;

            if (playerTran != null && playerTran.tag == "Player")
            {
                findPlayer = true;
            }
            else
            {
                findPlayer = false;
                playerTran = null;
            }
        }
        public override void ApplyDamage(Entity attacker, int damageHP)
        {
            base.ApplyDamage(attacker, damageHP);

            if (!currentHit)
            {
                currentHit = true;
            }

            CheckData();
        }
        private void CheckData()
        {
            if (enemyEntityData.CurrentHP <= 0)
            {
                int ControllerFormSerialId = GameEntry.DataNode.GetData<VarInt32>(Constant.ControllerFormSerialId);
                var con = GameEntry.UI.GetUIForm(ControllerFormSerialId).GetComponent<ControllerForm>();
                con.GetEXPUpdate(enemyEntityData.SelfEXP);
                con.GetKillUpdate(1);
            }
        }
        private bool once;
        private void OnTriggerEnter2D(Collider2D collision)
        {
            //敌人攻击玩家
            if (collision.transform.tag == "Player" && once == false)
            {
                PlayerEntity player = collision.gameObject?.GetComponent<PlayerEntity>();

                EnemyEntity enemy = transform?.GetComponent<EnemyEntity>();
                if (!player || !enemy) return;
                if (enemy && !player.animHit)
                {
                    player.ApplyDamage(player, enemy.enemyEntityData.Attack - player.playerEntityData.Defense);

                    player.HitAddForce(this);
                   
                }
                once = true;
                GameEntry.TimerComponent.AddOnceTimer(100, () => { once = false; });

            }
            //玩家触碰到死亡线
            if (collision.gameObject.name == "DeathLine")
            {
                enemyEntityData.CurrentHP = 0;
                if (gameObject.tag == "Enemy")
                {
                    CheckData();
                    OnDead(null);
                }

            }

        }
        private void OnDrawGizmos()
        {
            Gizmos.color = Color.green;
            
            Gizmos.DrawWireSphere((Vector2)transform.position + groundOffset, checkRadius);
            Gizmos.DrawWireSphere((Vector2)transform.position + touchLeftOffset, checkRadius);
            Gizmos.DrawWireSphere((Vector2)transform.position + touchRightOffset, checkRadius);


            Gizmos.color = Color.red;
   
            Vector3 arg1 = (Vector2)transform.position + rayOffsetPoint;
            Vector3 arg2= (Vector2)transform.position + rayOffsetPoint+new Vector2 ((faceDir.x < 0 ? -findPlayerRayCount : findPlayerRayCount),0);
            Gizmos.DrawLine(arg1,arg2);
        }
    }
}
